﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using MathExpression;

namespace SimplexSolver
{
    public class TargetFunction
    {
        public ReadOnlyCollection<IMathExpression> Coefs
        {
            get { return _coefs.AsReadOnly(); }
        }

        private readonly List<IMathExpression> _coefs;

        public IMathExpression FreeValue { get; private set; }

        public EDirection Direction { get; private set; }

        public TargetFunction(IEnumerable<IMathExpression> coefs, EDirection direction, IMathExpression freeValue = null)
        {
            _coefs = new List<IMathExpression>(coefs);
            if (freeValue == null)
            {
                freeValue = ExpressionFactory.Create(0.0);
            }
            FreeValue = freeValue.Clone();
            Direction = direction;
        }

        public TargetFunction(TargetFunction target) : this(target.Coefs, target.Direction, target.FreeValue)
        {
        }

        public IMathExpression GetValueOf(IMathExpression[] solutionX)
        {
            if (solutionX.Length != _coefs.Count)
            {
                throw new ArgumentOutOfRangeException("Target function row size is not equal to solution vector size");
            }
            int varsCount = solutionX.Length;
            IMathExpression value = ExpressionFactory.Create(0.0);
            IMathExpression[] targetRow = _coefs.ToArray();
            for (int i = 0; i < varsCount; i++)
            {
                IMathExpression mult = solutionX[i].Multiply(targetRow[i]);
                value = value.Add(mult);
            }
            return value;
        }

        public enum EDirection
        {
            Min,
            Max
        }
    }
}